#include "svmscorewidget.h"

#include <QPainter>
#include <QPaintEvent>
#include <QTimer>

const double SVMScoreWidget::step = double(1)/45;

SVMScoreWidget::SVMScoreWidget(QWidget *parent) :
    score(0),
    elapsed(0),
    QWidget(parent)
{
}

void SVMScoreWidget::setSVMScore(const double &svmScore)
{
    if (svmScore > 1) score = 1;
    else if (svmScore < -1) score = -1;
    else score = svmScore;
    elapsed = 0;
    animate();
}

void SVMScoreWidget::animate()
{
    if (elapsed != score) {
        if (score > 0) {
            elapsed += step;
            elapsed = elapsed>score?score:elapsed;
        } else {
            elapsed -= step;
            elapsed = elapsed<score?score:elapsed;
        }
        QTimer::singleShot(50, this, SLOT(animate()));
    }
    repaint();
}

void SVMScoreWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    static const QPoint hand[4] = {
        QPoint(5, 0),
        QPoint(0, 8),
        QPoint(-5, 0),
        QPoint(0, -80)
    };

    painter.translate(width() / 2, height() / 2);
    int side = qMin(width(), height());
    painter.scale(side / 200.0, side / 200.0);

    painter.setPen(Qt::white);
    painter.setBrush(Qt::NoBrush);
    painter.drawArc(QRect(-96, -96, 192, 192), 0, 180*16);
    painter.save();
    for (int i = 0; i <= 20; ++i) {
        if (i%5) painter.drawLine(-96, 0, -92, 0);
        else painter.drawLine(-96, 0, -88, 0);
        painter.rotate(9);
    }
    painter.restore();
    int line = painter.fontMetrics().lineSpacing();
    painter.drawText(-96, line, tr("Malignant"));
    painter.drawText(96-painter.fontMetrics().boundingRect(tr("Benign")).width(), line, tr("Benign"));
    QSize textSize  = painter.fontMetrics().boundingRect("-0.0000").size();
    QRect textRect(-textSize.width()/2, line*2, textSize.width(), textSize.height());
    textRect.adjust(-line*0.8, -line*0.2, line*0.8, line*0.2);
    painter.drawRect(textRect);

    painter.setPen(elapsed<0?Qt::red:Qt::green);
    painter.setBrush(elapsed<0?Qt::red:Qt::green);
    painter.save();
    painter.setPen(Qt::NoPen);
    painter.rotate(elapsed*90);
    painter.drawConvexPolygon(hand, 4);
    painter.setBrush(Qt::white);
    painter.drawEllipse(QPoint(0, 0), 2, 2);
    painter.restore();

    painter.drawText(textRect, Qt::AlignCenter, QString::number(elapsed, 'f', 4));

    QWidget::paintEvent(event);
}
